<template>
	<el-dialog v-model="dialogVisible" :title="`${title}套餐`" width="60%" center @close="dialogClose">
		<el-scrollbar height="600px">
			<el-form :model="form" label-width="120px">
				<el-form-item label="套餐名称">
					<el-input v-model="form.name" placeholder="请输入" />
				</el-form-item>

				<el-form-item label="套餐分类">
					<el-select v-model="form.categoryId" placeholder="请选择" style="width: 100%">
						<el-option v-for="item in comboList" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>

				<el-form-item label="套餐售价">
					<el-input-number v-model="form.price" :min="1" controls-position="right" style="width: 100%; text-align: left" />
				</el-form-item>

				<el-form-item label="套餐菜品">
					<el-row style="width: 100%">
						<el-col :span="24">
							<el-button type="primary" color="#ffc200" @click="dishDialogIsShow = true">添加菜品</el-button>
						</el-col>

						<el-col :span="24">
							<el-table :data="form.setmealDishes" style="width: 100%">
								<el-table-column prop="name" label="名称" align="center" />
								<el-table-column prop="price" label="原价" align="center" />
								<el-table-column prop="" label="份数" align="center">
									<template #default="{ row }">
										<el-input-number v-model="row.copies" :min="1" :step="1" />
									</template>
								</el-table-column>

								<el-table-column label="操作" align="center">
									<template #default="scope">
										<el-button text @click="form.setmealDishes.splice(scope.$index, 1)" style="color: red">删除</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-col>
					</el-row>
				</el-form-item>

				<el-form-item label="图片">
					<el-upload
						v-if="!url"
						v-model:file-list="fileList"
						action="api/common/upload"
						list-type="picture-card"
						:on-success="handleSuccess"
						:show-file-list="false"
						:limit="1">
						<el-icon>
							<Plus />
						</el-icon>
					</el-upload>

					<el-image
						v-else
						style="width: 148px; height: 148px"
						:src="url"
						:zoom-rate="1.2"
						:preview-src-list="srcList"
						fit="cover" />
				</el-form-item>

				<el-form-item label="描述">
					<el-input v-model="form.description" :autosize="{ minRows: 3, maxRows: 9 }" type="textarea" placeholder="请输入" />
				</el-form-item>
			</el-form>
		</el-scrollbar>

		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogClose">取消</el-button>
				<el-button color="#ffc200" @click="saveClick"> 确认 </el-button>
			</span>
		</template>

		<AddDishDialog
			:dishList="dishList"
			:dishDialogIsShow="dishDialogIsShow"
			@dishDialogClose="dishDialogClose"
			@getDishParam="getDishParam" />
	</el-dialog>
</template>

<script lang="ts" setup name="DishesDialog">
	import { toRefs, defineProps, defineEmits, ref, onMounted } from 'vue'
	import { ElMessage, type UploadUserFile } from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import { useRouter } from 'vue-router'
	import { downloadImg, getCategoryList, saveSetmealWithDish, getSetmealInfo, updateSetmeal } from '@/api/index'
	import AddDishDialog from './AddDishDialog.vue'

	const router = useRouter()

	interface IFormType {
		name: string
		image: string
		categoryId: string
		price: number | null
		status: number | null
		description: string
		setmealDishes: IDishType[]
	}

	const form = ref<IFormType>({
		name: '',
		image: '',
		categoryId: '',
		price: null,
		status: 1,
		description: '',
		setmealDishes: []
	})

	const fileList = ref<UploadUserFile[]>([])

	interface IDialogParam {
		dialogVisible: boolean
		title: string
		id?: string
	}

	// 接收父组件传参
	const props = defineProps<{
		dialogParam: IDialogParam
	}>()

	const { dialogVisible, title } = toRefs(props.dialogParam)

	const emit = defineEmits(['dialogClose'])
	const dialogClose = () => {
		emit('dialogClose')
	}

	const url = ref() // 图片url
	const srcList = ref<string[]>([]) // 预览图片数组

	const handleSuccess = async (response: { data: string; code: number; msg: string }) => {
		// 判断用户是否登录
		response.code === 0 ? (response.msg === 'NOTLOGIN' ? router.push('/login') : true) : true

		downImg(response.data)
		form.value.image = response.data
	}

	/**
	 * 下载图片
	 * @param data 图片名称
	 */
	const downImg = async (data: string) => {
		// 获取图片地址
		const res = await downloadImg<Blob>({ name: data })
		// 使用 window.URL.createObjectURL 将图片流转为地址
		const path = window.URL.createObjectURL(new Blob([res as any], { type: 'image/png' }))
		url.value = path
		srcList.value.push(path)
	}

	interface IDishType {
		id: string
		name: string
		categoryId: string
		price: number
		code: string
		image: string
		description: string
		copies: number
	}

	const getDishParam = (data: IDishType[]) => {
		form.value.setmealDishes = JSON.parse(JSON.stringify(data))
		dishDialogIsShow.value = false
	}

	interface IComboListType {
		name: string
		id: string
	}

	const comboList = ref<IComboListType[]>([])

	const dishList = ref<IComboListType[]>([])

	const dishDialogIsShow = ref<boolean>(false)

	const dishDialogClose = () => {
		dishDialogIsShow.value = false
	}

	const saveClick = async () => {
		try {
			form.value.status = 1
			if (props.dialogParam.title === '新增') {
				await saveSetmealWithDish<string>(form.value)
			} else {
				updateSetmeal<string>(form.value)
			}
			ElMessage.success('操作成功')
			emit('dialogClose')
		} catch (error) {
			ElMessage.error(error as string)
		}
	}

	const initData = async () => {
		// 获取套餐分类数据
		const { data: combolist } = await getCategoryList<IComboListType[]>({ type: 2 })
		comboList.value = combolist

		// 获取菜品分类数据
		const { data: dishlist } = await getCategoryList<IComboListType[]>({ type: 1 })
		dishList.value = dishlist

		if (props.dialogParam.id) {
			try {
				const res = await getSetmealInfo<IFormType>(props.dialogParam.id)
				form.value = res.data
				downImg(res.data.image)
			} catch (error) {
				ElMessage.error(error as string)
			}
		}
	}

	onMounted(() => {
		initData()
	})
</script>

<style scoped lang="scss"></style>
